package com.yuwj.chinaa.util;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

import java.util.ArrayList;
import java.util.Map;

/**
 * GsonUtil,用于将json转化为Entity 或者 List<Entity>
 */
public class GsonUtil {


    public static String bean2Json(Object obj) {
        Gson gson = new GsonBuilder().create();
        return gson.toJson(obj);
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(jsonStr, objClass);
    }

    /**
     * 此方法可以解决返回值遍历时强转为T类型时出现的强制转化异常.
     *
     * @param jsonStr
     * @param objClass
     * @return
     */
    public static <T> ArrayList<T> json2BeanList(String jsonStr, Class<T> objClass) {
        Gson gson = new GsonBuilder().create();
        ArrayList<T> mList = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(jsonStr).getAsJsonArray();
        for (final JsonElement elem : array) {
            mList.add(gson.fromJson(elem, objClass));
        }
        return mList;
    }

    public static <T> String beanList2Json(T obj) {
        Gson gson = new GsonBuilder().create();
        return gson.toJson(obj);

    }

    /**
     * 把混乱的json字符串整理成缩进的json字符串
     *
     * @param uglyJsonStr
     * @return
     */
    public static String jsonFormatter(String uglyJsonStr) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(uglyJsonStr);
        String prettyJsonString = gson.toJson(je);
        return prettyJsonString;
    }

    /**
     * String 转化为map
     *
     * @param jsonStr
     * @return
     */
    public static Map json2Map(String jsonStr) {
        Map map = null;
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        if (!TextUtils.isEmpty(jsonStr)) {
            try {
                map = gson.fromJson(jsonStr, Map.class);
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
